/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.soc.cs5226.gui.security.beans;

import javax.faces.application.FacesMessage;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.http.*;

import java.io.Serializable;

/**
 *
 * @author huijia
 */
@ManagedBean
@SessionScoped
public class LoginBean implements Serializable{

    private String username;
    private String password;
    private boolean isLoggedIn = false;
    
    private static final String LOGIN_PAGE = "login.xhtml";
    private static final String MAIN_PAGE = "index.xhtml";
    private static final String LOGOUT_PAGE = "login.xhtml?faces-redirect=true";

    public String getUsername() {
            return username;
    }

    public void setUsername(String username) {
            this.username = username;
    }

    public String getPassword() {
            return password;
    }

    public void setPassword(String password) {
            this.password = password;
    }

    public boolean isIsLoggedIn() {
        return isLoggedIn;
    }

    public void setIsLoggedIn(boolean isLoggedIn) {
        this.isLoggedIn = isLoggedIn;
    }

    public String login() {
        FacesMessage msg = null;
        String pageToGo = LOGIN_PAGE;

        if(username != null  && username.equals("admin") && password != null  && password.equals("admin")) {
            setIsLoggedIn(true);
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", username);
            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            HttpSession session = request.getSession(true);
            if (session.isNew()==false) {
                session.invalidate();
                session = request.getSession(true);
            }
            session.setAttribute("login", "true");
            pageToGo = MAIN_PAGE;
        } else {
            setIsLoggedIn(false);
            msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Invalid credentials");
            pageToGo = LOGIN_PAGE;
        }
        
        FacesContext.getCurrentInstance().addMessage(null, msg);
        return pageToGo;
    }
    
    public String logout() {
        setIsLoggedIn(false);
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        HttpSession session = request.getSession(false);
        session.removeAttribute("login");
        session.invalidate();
        return LOGOUT_PAGE;
    }
}
						
